import React, { useState, useEffect, useMemo } from 'react';
import { 
  Table, Input, Select, DatePicker, Button, Space, 
  InputNumber, Checkbox, Popover, Divider, Tag, Row, Col 
} from 'antd';
// import {  ColumnsOutlined } from '@ant-design/icons';
// 替换原来的整体导入
import SearchOutlined from '@ant-design/icons/SearchOutlined';
import FilterOutlined from '@ant-design/icons/FilterOutlined';
// import ColumnsOutlined from '@ant-design/icons/ColumnsOutlined';
import moment from 'moment';

// 模拟用户数据
const mockUserData = Array.from({ length: 100 }, (_, i) => ({
  id: `USR${1000 + i}`,
  name: [`张三`, `李四`, `王五`, `赵六`][i % 4],
  age: 20 + (i % 30),
  gender: i % 2 === 0 ? 'male' : 'female',
  department: ['技术部', '市场部', '财务部', '人力资源部'][i % 4],
  position: ['前端开发', '后端开发', '产品经理', '测试工程师', 'UI设计师'][i % 5],
  entryDate: moment().subtract(i % 365, 'days'), // 入职日期
  status: ['在职', '离职', '休假', '试用期'][i % 4],
  salary: 5000 + (i % 20) * 1000, // 薪资范围
}));

const ComplexTable = () => {
  // 状态管理
  const [searchParams, setSearchParams] = useState({
    name: '', // 姓名模糊搜索
    department: '', // 部门筛选
    status: [], // 状态多选
    ageRange: [20, 60], // 年龄范围
    entryDateRange: [], // 入职日期范围
    salaryMin: 0, // 最低薪资
  });
  const [tableData, setTableData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [visibleColumns, setVisibleColumns] = useState([
    'id', 'name', 'age', 'gender', 'department', 'position', 'entryDate', 'status', 'salary'
  ]); // 显示的列
  const [sortInfo, setSortInfo] = useState({
    field: '',
    order: '', // 'ascend' | 'descend'
  });

  // 高级筛选弹窗状态
  const [advancedFilterVisible, setAdvancedFilterVisible] = useState(false);

  // 处理搜索参数变化
  const handleParamChange = (key, value) => {
    setSearchParams(prev => ({ ...prev, [key]: value }));
    // 重置分页
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 筛选数据（模拟接口请求）
  useEffect(() => {
    // 模拟接口延迟
    const timer = setTimeout(() => {
      // 1. 基础筛选
      let filteredData = [...mockUserData];
      
      // 姓名模糊搜索
      if (searchParams.name) {
        filteredData = filteredData.filter(item => 
          item.name.includes(searchParams.name)
        );
      }
      
      // 部门筛选
      if (searchParams.department) {
        filteredData = filteredData.filter(item => 
          item.department === searchParams.department
        );
      }
      
      // 状态多选筛选
      if (searchParams.status.length > 0) {
        filteredData = filteredData.filter(item => 
          searchParams.status.includes(item.status)
        );
      }
      
      // 年龄范围筛选
      filteredData = filteredData.filter(item => 
        item.age >= searchParams.ageRange[0] && item.age <= searchParams.ageRange[1]
      );
      
      // 入职日期范围筛选
      if (searchParams.entryDateRange.length === 2) {
        filteredData = filteredData.filter(item => 
          item.entryDate.isBetween(
            searchParams.entryDateRange[0], 
            searchParams.entryDateRange[1], 
            null, 
            '[]'
          )
        );
      }
      
      // 薪资筛选
      if (searchParams.salaryMin > 0) {
        filteredData = filteredData.filter(item => 
          item.salary >= searchParams.salaryMin
        );
      }
      
      // 2. 排序
      if (sortInfo.field && sortInfo.order) {
        filteredData.sort((a, b) => {
          const orderFactor = sortInfo.order === 'ascend' ? 1 : -1;
          if (a[sortInfo.field] < b[sortInfo.field]) return -1 * orderFactor;
          if (a[sortInfo.field] > b[sortInfo.field]) return 1 * orderFactor;
          return 0;
        });
      }
      
      // 3. 分页处理
      const total = filteredData.length;
      const startIndex = (pagination.current - 1) * pagination.pageSize;
      const endIndex = startIndex + pagination.pageSize;
      const paginatedData = filteredData.slice(startIndex, endIndex);
      
      setTableData(paginatedData);
      setPagination(prev => ({ ...prev, total }));
    }, 300); // 模拟接口延迟
    
    return () => clearTimeout(timer);
  }, [searchParams, pagination, sortInfo]);

  // 表格列配置（根据visibleColumns动态生成）
  const columns = useMemo(() => [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      sorter: true, // 支持排序
      visible: visibleColumns.includes('id'),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      visible: visibleColumns.includes('name'),
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      sorter: true,
      visible: visibleColumns.includes('age'),
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (gender) => (
        <Tag color={gender === 'male' ? 'blue' : 'pink'}>
          {gender === 'male' ? '男' : '女'}
        </Tag>
      ),
      visible: visibleColumns.includes('gender'),
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      sorter: true,
      visible: visibleColumns.includes('department'),
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      visible: visibleColumns.includes('position'),
    },
    {
      title: '入职日期',
      dataIndex: 'entryDate',
      key: 'entryDate',
      render: (date) => date.format('YYYY-MM-DD'),
      sorter: true,
      visible: visibleColumns.includes('entryDate'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const colorMap = {
          '在职': 'green',
          '离职': 'red',
          '休假': 'orange',
          '试用期': 'purple',
        };
        return <Tag color={colorMap[status]}>{status}</Tag>;
      },
      sorter: true,
      visible: visibleColumns.includes('status'),
    },
    {
      title: '薪资(元)',
      dataIndex: 'salary',
      key: 'salary',
      render: (salary) => `¥${salary.toLocaleString()}`,
      sorter: true,
      visible: visibleColumns.includes('salary'),
    },
  ].filter(col => col.visible), [visibleColumns]);

  // 处理表格排序
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
    if (sorter.field) {
      setSortInfo({
        field: sorter.field,
        order: sorter.order,
      });
    }
  };

  // 重置搜索条件
  const resetSearch = () => {
    setSearchParams({
      name: '',
      department: '',
      status: [],
      ageRange: [20, 60],
      entryDateRange: [],
      salaryMin: 0,
    });
    setPagination({ current: 1, pageSize: 10, total: 0 });
    setSortInfo({ field: '', order: '' });
  };

  // 列显示控制弹窗内容
  const columnControlContent = (
    <div style={{ padding: 16 }}>
      {columns.map(col => (
        <Checkbox 
          key={col.key}
          checked={visibleColumns.includes(col.key)}
          onChange={(e) => {
            if (e.target.checked) {
              setVisibleColumns(prev => [...prev, col.key]);
            } else {
              setVisibleColumns(prev => prev.filter(key => key !== col.key));
            }
          }}
        >
          {col.title}
        </Checkbox>
      ))}
    </div>
  );

  return (
    <div > 
      {/* 搜索区域 */}
      <div style={{ marginBottom: 16, background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
        <Row gutter={[16, 16]}>
          {/* 基础搜索项 */}
          <Col xs={24} sm={12} md={6}>
            <Input 
              placeholder="请输入姓名" 
              value={searchParams.name}
              onChange={(e) => handleParamChange('name', e.target.value)}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="请选择部门"
              style={{ width: '100%' }}
              value={searchParams.department}
              onChange={(value) => handleParamChange('department', value)}
              allowClear
            >
              <Select.Option value="技术部">技术部</Select.Option>
              <Select.Option value="市场部">市场部</Select.Option>
              <Select.Option value="财务部">财务部</Select.Option>
              <Select.Option value="人力资源部">人力资源部</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="请选择状态"
              style={{ width: '100%' }}
              value={searchParams.status}
              onChange={(value) => handleParamChange('status', value)}
              mode="multiple"
              allowClear
            >
              <Select.Option value="在职">在职</Select.Option>
              <Select.Option value="离职">离职</Select.Option>
              <Select.Option value="休假">休假</Select.Option>
              <Select.Option value="试用期">试用期</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Space>
              <Button 
                type="primary" 
                icon={<SearchOutlined />}
                onClick={() => {}} // 触发搜索（实际已通过useEffect自动触发）
              >
                搜索
              </Button>
              <Button onClick={resetSearch}>重置</Button>
              <Popover 
                content={columnControlContent} 
                title="列显示设置"
                trigger="click"
              >
                <Button >列设置</Button>
              </Popover>
            </Space>
          </Col>
        </Row>

        {/* 高级筛选（可折叠） */}
        <Divider orientation="left" style={{ marginTop: 16 }}>
          <Button 
            type="text" 
            icon={<FilterOutlined />}
            onClick={() => setAdvancedFilterVisible(!advancedFilterVisible)}
          >
            高级筛选
          </Button>
        </Divider>
        
        {advancedFilterVisible && (
          <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
            <Col xs={24} sm={12} md={6}>
              <Space>
                <span>年龄范围：</span>
                <InputNumber
                  min={18}
                  max={80}
                  value={searchParams.ageRange[0]}
                  onChange={(value) => handleParamChange('ageRange', [value, searchParams.ageRange[1]])}
                />
                <span>至</span>
                <InputNumber
                  min={18}
                  max={80}
                  value={searchParams.ageRange[1]}
                  onChange={(value) => handleParamChange('ageRange', [searchParams.ageRange[0], value])}
                />
              </Space>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <DatePicker.RangePicker
                placeholder={['入职开始日期', '入职结束日期']}
                value={searchParams.entryDateRange}
                onChange={(value) => handleParamChange('entryDateRange', value)}
                format="YYYY-MM-DD"
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <InputNumber
                placeholder="最低薪资"
                style={{ width: '100%' }}
                value={searchParams.salaryMin}
                onChange={(value) => handleParamChange('salaryMin', value)}
                formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
                min={0}
              />
            </Col>
          </Row>
        )}
      </div>

      {/* 表格区域 */}
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条数据`,
        }}
        onChange={handleTableChange}
        scroll={{ x: 1200 }} // 横向滚动（适配多列）
        bordered
        size="middle"
      />
    </div>
  );
};

export default ComplexTable;